package com.gxa.controller;
import com.gxa.util.JsonResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.Map;

/**
 * @Author 杨天可
 * @Date 2020/9/17 14:22
 * @Version 1.0
 */

@ControllerAdvice  //将当前类作为全局异常的总处理入口
public class ExceptionController {

    @ExceptionHandler(Exception.class)
    public void handleException(Exception e){
        //系统异常。记录日志
        System.out.println("=================================================================");
        System.out.println("异常发生的原因："+e.getMessage());
        System.out.println("异常的类型："+e.toString());
        //输出到控制台
        e.printStackTrace();

        //记录到日志
        StackTraceElement[] stackTrace = e.getStackTrace();
        for(StackTraceElement stackTraceElement:stackTrace){

            //用log4j2记录日志
            System.out.println(stackTraceElement.toString());
        }
        System.out.println("=================================================================");
    }

    @ExceptionHandler(BusinessException.class)
    public Map handleBusinessException(BusinessException e){
        //业务异常，反馈给前端
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("500");
        jsonResult.setMsg(e.getMessage());

        return jsonResult.getValues();
    }





}
